package itheima.thread;

import itheima.ui.ClientChatFrame;

import javax.swing.*;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ReceiveThread extends Thread {

    private Socket socket;
    private DataInputStream dis;

    private ClientChatFrame clientChatFrame;

    public ReceiveThread(Socket socket, ClientChatFrame clientChatFrame) {
        this.socket = socket;
        this.clientChatFrame = clientChatFrame;
        try {
            dis = new DataInputStream(socket.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                // 接收消息类型 1.登录消息 2.群聊消息
                int type = dis.readInt();
                switch (type) {
                    case 1:
                        // 服务器发来的在线人数信息
                        updateOnlineCount();
                        break;
                    case 2:
                        // 群聊消息
                        String message = dis.readUTF();
                        clientChatFrame.chatArea.append(message);
                        break;
                    default:
                        break;
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }

    private void updateOnlineCount() {
        try {
            int onlineCount = dis.readInt();
            // 更新在线人数
            clientChatFrame.onlineUsersScrollPane.setBorder(BorderFactory.createTitledBorder("在线人数: " + onlineCount));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < onlineCount; i++) {
                String username = dis.readUTF();
                sb.append(username).append("\r\n");
            }
            clientChatFrame.onlineUsersArea.setText(sb.toString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
